using System;
using WebMatrix.WebData;

namespace Se.Framework.Web.Mvc.Filters
{
    public class SimpleMembershipInitializerAttribute : InitializerAttribute
    {
        public SimpleMembershipInitializerAttribute(string key, string connectionStringName = "DefaultConnection", string userTableName = "User", string userIdColumn = "Id", string userNameColumn = "UserName", bool autoCreateTables = true)
            :base(key)
        {
            this.AutoCreateTables = autoCreateTables;
            this.UserNameColumn = userNameColumn;
            this.UserIdColumn = userIdColumn;
            this.ConnectionStringName = connectionStringName;
            this.UserTableName = userTableName;
        }

        public Type ContextType { get; private set; }

        public string UserTableName { get; private set; }

        public string ConnectionStringName { get; private set; }

        public string UserIdColumn { get; private set; }

        public string UserNameColumn { get; private set; }

        public bool AutoCreateTables { get; private set; }
          
        protected override void Initialize()
        {
            try
            {
                WebSecurity.InitializeDatabaseConnection(this.ConnectionStringName, this.UserTableName, this.UserIdColumn, this.UserNameColumn, this.AutoCreateTables);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
            }
        }
    }
}